package com.iyoudoock.citymine.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.iyoudoock.citymine.BaseActivity;
import com.iyoudoock.citymine.R;
import com.iyoudoock.citymine.activity.user.PersonCenterActivity;
import com.iyoudoock.citymine.bean.AroundPeopleBean;
import com.iyoudoock.citymine.constants.HttpUtils;
import com.iyoudoock.citymine.constants.Key;
import com.iyoudoock.citymine.constants.Map;
import com.iyoudoock.citymine.constants.Value;
import com.iyoudoock.citymine.utils.MapUtils;
import com.iyoudoock.citymine.widget.MarqueeTextView;
import com.kvin.toolkit.constants.Interaction;
import com.kvin.toolkit.utils.JumpUtils;
import com.kvin.toolkit.utils.ListUtils;
import com.kvin.toolkit.utils.TipsUtils;
import com.kvin.toolkit.utils.ToastUtils;
import com.kvin.toolkit.utils.http.JsonUtils;
import com.kvin.toolkit.utils.system.NetUtils;
import com.kvin.toolkit.utils.system.PermissionUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RecycleBinActivity extends BaseActivity {

    @BindView(R.id.m_map_view)
    MapView mMapView;
    @BindView(R.id.notice_tv)
    MarqueeTextView noticeTv;
    @BindView(R.id.close_container)
    RelativeLayout closeIv;
    @BindView(R.id.notice_container)
    LinearLayout noticeContainer;
    @BindView(R.id.location_iv)
    ImageView locationIv;
    @BindView(R.id.refresh_iv)
    ImageView refreshIv;
    @BindView(R.id.refresh_container)
    LinearLayout refreshContainer;

    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private boolean isFirstLoc;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle_bin);
        ButterKnife.bind(this);
    }


    @Override
    public void initNav() {
        setTitle("回收站");
    }

    @Override
    public void init() {
        initTips();
        mJsonUtils = JsonUtils.getInstance();
        //init base map
        mMapView.removeViewAt(2);//zoom up or down  view
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        // mBaiduMap.setOnMarkerClickListener(mOnMarkerClickListener);
        mBaiduMap.setTrafficEnabled(true);
        mBaiduMap.setBuildingsEnabled(true);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(Map.ZOOM_SCALE);// 2公里左右
        mBaiduMap.setMapStatus(msu);

        //init location related
        mBaiduMap.setMyLocationEnabled(true);//
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(new OnLocationListener());
        mLocationClient.setLocOption(MapUtils.getOption());//bind location configs

        noticeTv.setText("天津部分地区已经开通回收服务，其他地区将陆续开通        ");
        this.closeIv.setOnClickListener(this);
        this.refreshIv.setOnClickListener(this);
        this.locationIv.setOnClickListener(this);
        this.mBaiduMap.setOnMarkerClickListener(mOnMarkerClickListener);
    }

    /**
     * init tips
     */
    private void initTips() {
        mTips = TipsUtils.getInstance(this);
        mTips.setTitle("温馨提示");
        mTips.setDesc("请在18点~24点之间更新价格、品类");
        mTips.setOnCancelClickListener(null);
        mTips.setOnConfirmClickListener(null);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_container:
                noticeContainer.setVisibility(View.INVISIBLE);
                break;
            case R.id.location_iv:
                updateLocation(Double.valueOf(mLatitude), Double.valueOf(mLongitude));
                break;
            case R.id.refresh_iv:
                searchAroundRecycler();
                break;
        }
    }

    /**
     * marker click listener
     */
    private BaiduMap.OnMarkerClickListener mOnMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            JumpUtils.jumpWithParams(getActivity(), PersonCenterActivity.class, marker.getExtraInfo());
            return true;
        }
    };

    /**
     * search around recycler
     */
    private void searchAroundRecycler() {
        params = HttpUtils.getAroundRecyclerParams(mUid, mLongitude, mLatitude, "3000", searchType());
        mJsonUtils.post(HttpUtils.AROUND_RECYCLER_URL, params, this, Value.Flag.AROUND_RECYCLER);
    }


    @Override
    public void onSuccess(JSONObject response, String flag) {
        super.onSuccess(response, flag);
        if (response == null) return;
        try {
            if (flag.equals(Value.Flag.AROUND_RECYCLER)) {
                String s = response.getString(Key.Tag.DATA);
                List<AroundPeopleBean> list = JSON.parseArray(s, AroundPeopleBean.class);
                if (ListUtils.isEmpty(list)) return;
                LatLngBounds.Builder mBuilder = new LatLngBounds.Builder();
                for (int i = 0; i < list.size(); i++) {
                    AroundPeopleBean bean = list.get(i);
                    LatLng mLatLng = new LatLng(bean.getLatitude(), bean.getLongitude());
                    OverlayOptions options = new MarkerOptions().position(mLatLng).icon(getOverlay(bean.getType())).zIndex(7);

                    Marker marker = (Marker) mBaiduMap.addOverlay(options);
                    mBundle = new Bundle();
                    mBundle.putParcelable(Key.Tag.PEOPLE, bean);
                    marker.setExtraInfo(mBundle);
                    mBuilder.include(marker.getPosition());
                }
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(mBuilder.build()));
                mTips.show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onFailure(IOException e, String flag) {
        super.onFailure(e, flag);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();

        startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
    }

    /**
     * update location
     */
    private void updateLocation(double lat, double lon) {
        LatLng ll = new LatLng(lat, lon);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(u);
    }

    /**
     * start location
     */
    private void startLocation() {
        isFirstLoc = true;
        // 开始定位
        if (!PermissionUtils.isPermitted(getActivity(), Interaction.Permissions.LOC)) {
            PermissionUtils.requestPermission(getActivity(), Interaction.Permissions.LOC, Interaction.Code.REQUEST_LOCATION);
        } else {
            launchLocation();
        } // isFirst = true;
    }

    /**
     * start location
     */
    private void launchLocation() {
        if (!NetUtils.isNetConnected(this)) {
            ToastUtils.simpleToast(getActivity(), "当前没有网络，请检查！");
            return;
        } else if (mBaiduMap != null) {
            //mBaiduMap.setMyLocationEnabled(true);
            if (!mLocationClient.isStarted()) {
                // isFirst = true;
                mLocationClient.start();
            }
        }
    }

    /**
     * 定位SDK监听函数
     */
    public class OnLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                mLatitude = String.valueOf(location.getLatitude());
                mLongitude = String.valueOf(location.getLongitude());
                mPersistentUtils.writeString(Key.User.LATITUDE, mLatitude);
                mPersistentUtils.writeString(Key.User.LONGITUDE, mLongitude);
                updateLocation(location.getLatitude(), location.getLongitude());
                uploadLatLng(mLatitude,mLongitude);
            }


        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

}
